var vue = new Vue({
    el: '#app',
    data: function () {
        return {
            // 数据源相关的数据
            dataSource: [],// 数据源集
            dbName: '',// 搜索数据源的配置名称
            dataSourceLoading: true,// 搜索数据源集时加载动画的控制
            dataSourceSin: {},// 选择的数据源
            saveDataSourceLoading: false,// 保存数据源时加载动画的控制
            saveDataSource: {// 保存数据源
                id: '',
                db_name: '',
                dataType: '',
                url: '',
                libraryName: '',
                username: '',
                password: ''
            },
            dataSourceVisible: false,// 控制添加数据源的开闭
            page: {// 数据源分页
                currentPage: 1, //初始页
                pageSize: 10, //每页的数据
                totalCount: 0 //总数据
            },

            // 策略配置相关的数据
            strategyName: '',
            strategyList: [],
            strategy: {
                id: '',
                name: '',
                author: '',
                tableNameList: [],
                parentPath: '',
                entityPack: '',
                servicePack: '',
                serviceImplPack: '',
                mapperPack: '',
                ignoreTablePrefixs: '',
                enableSwagger: false,
                enableLombok: false,
                ignoreBooleanPrefix: false,
                superMapperClass: '',
                logicDeleteColumnName: '',
                versionColumnName: '',
                fillsList: '',
                superServiceImplClass: '',
            },
            saveStrategyVisible: false,
            strategyVisible: false,// 控制策略配置的开关

            // 表名集合相关的数据
            tablePage: {
                currentPage: 1, //初始页
                pageSize: 10, //每页的数据
                totalCount: 0 //总数据
            },
            tableList: [],
            tableLoading: false,
            tableName: '',
            manyTableList: [],

            // 自动填充相关的数据
            fillList: [],
            fillLoading: false,
            saveFillLoading: false,
            saveFill: {
                id: "",
                columnName: "",
                fieldFillType: "",
            },
            form: {},
            downloadLoading: false,
            menuVisible: false,

            // 示例数据
            exampleData: {
                exampleDataVisible: false,
                mysql: "jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true",
                oracle: "jdbc:oracle:thin:@127.0.0.1:1521:orcl",
                db2: "jdbc:db2://127.0.0.1:50000/test",
                king: "jdbc:kingbase8://127.0.0.1:54321/test"
            }
        }
    },
    methods: {
        exampleUrl() {
            this.exampleData.exampleDataVisible = true;
        },
        downloadFile() {
            var params = {
                dataSourceInfoId: this.dataSourceSin.id,
                strategyInfoId: this.strategy.id,
                tableNameList: this.manyTableList
            }

            if (params.tableNameList.length > 0) {
                this.downloadLoading = true;
                axiosDoAjax('post', ip + '/generate', params, function (res) {
                    const a = document.createElement('a');
                    a.style.display = 'none';
                    a.download = 'javaFile.zip';
                    a.href = window.URL.createObjectURL(new Blob([res]));
                    a.click();

                    vueObj.downloadLoading = false;
                    vueObj.showMsg("生成代码成功");
                }, function (error) {
                    vueObj.downloadLoading = false;
                }, { 'responseType': 'blob' });
            } else {
                this.showMsg("请选择表", 'warning');
            }
        },
        // 数据源-搜索
        searchDataSource(isSearch) {
            if (isSearch) {
                this.page.currentPage = 1;
            }
            this.dataSourceSin = {};
            this.dataSourceLoading = true;

            axiosDoAjax('GET', ip + '/dataSource/page', {
                currentPage: this.page.currentPage,
                pageSize: this.page.pageSize,
                dbName: this.dbName
            }, function (res) {
                if (res.code === 0) {
                    vueObj.dataSource = res.data.records;
                    vueObj.page.totalCount = res.data.total;
                }

                vueObj.dataSourceLoading = false;
            }, function (error) {
                vueObj.dataSourceLoading = false;
            })
        },
        // 数据源-编辑
        editDataSource() {
            if (this.dataSourceSin.id) {
                this.saveDataSource.id = this.dataSourceSin.id
                // 对象浅拷贝
                this.saveDataSource = Object.assign({}, this.dataSourceSin);
                this.dataSourceVisible = true
            } else {
                this.showMsg('请选择数据源...', 'warning');
            }
        },
        // 数据源-右键编辑
        editDataSourceRig(currentRow) {
            if (currentRow.id) {
                // 对象浅拷贝
                this.saveDataSource = Object.assign({}, currentRow);
                this.dataSourceVisible = true
            } else {
                this.showMsg('请选择数据源...', 'warning');
            }
        },
        // 数据源-连接
        connectDataSource(currentRow) {
            var currentDataSource = this.dataSourceSin;
            if (currentRow) {
                currentDataSource = currentRow;
            }

            if (currentDataSource) {
                this.dataSourceLoading = true;

                axiosDoAjax('post', ip + '/generate/connect', currentDataSource, function (res) {
                    if (res.code === 0) {
                        vueObj.showMsg(res.msg);
                    }

                    vueObj.dataSourceLoading = false;
                }, function (error) {
                    vueObj.dataSourceLoading = false;
                })
            } else {
                this.showMsg('请选择数据源...', 'warning');
            }
        },
        // 数据源-清空
        emptyDataSource() {
            var keys = Object.keys(this.saveDataSource);
            for (var i = 0; i < keys.length; i++) {
                this.saveDataSource[keys[i]] = '';
            }
        },
        // 数据源-行单击事件
        rowClick(row, column) {
            this.dataSourceSin = row;
            this.$refs.tb.clearSelection()
            this.$refs.tb.toggleRowSelection(this.dataSourceSin, true);
            this.searchTableList('锦');
        },
        // 数据源-保存
        saveDataSourceMet() {
            this.saveDataSourceLoading = true;

            axiosDoAjax('post', ip + '/dataSource/save', this.saveDataSource, function (res) {
                if (res.code === 0) {
                    vueObj.searchDataSource();
                    vueObj.dataSourceVisible = false;
                    vueObj.showMsg(res.msg);
                }

                vueObj.saveDataSourceLoading = false;
            }, function (error) {
                vueObj.saveDataSourceLoading = false;
            });
        },
        // 数据源-页大小
        sourcePageSize(size) {
            this.page.pageSize = size
            this.searchDataSource();
        },
        // 数据源-当前页
        sourceCurrentPage(currentPage) {
            this.page.currentPage = currentPage
            this.searchDataSource();
        },
        // 数据源-删除
        deleteDataSource(dbInfo) {
            this.$confirm('此操作将永久删除该配置: ' + dbInfo.dbName + '，是否继续?', '提示', {
                confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning'
            }).then(() => {
                this.dataSourceLoading = true;

                axiosDoAjax('get', ip + '/dataSource/delete', { 'id': dbInfo.id }, function (res) {
                    if (res.code === 0) {
                        vueObj.searchDataSource();
                        vueObj.showMsg(res.msg);
                    }

                    vueObj.dataSourceLoading = false;
                }, function (error) {
                    vueObj.dataSourceLoading = false;
                })
            });
        },
        // 数据源-增加
        addDataSource() {
            this.dataSourceVisible = true;
            this.emptyDataSource();
        },
        // 数据源-右键菜单功能
        rightClick(row, column, event) {
            this.testModeCode = row.testModeCode
            this.menuVisible = false // 先把模态框关死，目的是 第二次或者第n次右键鼠标的时候 它默认的是true
            this.menuVisible = true // 显示模态窗口，跳出自定义菜单栏
            event.preventDefault() //关闭浏览器右键默认事件
            this.CurrentRow = row
            var menu = document.querySelector('.menu')
            this.styleMenu(menu)
            this.rowClick(row);
        },
        foo() {
            // 取消鼠标监听事件 菜单栏
            this.menuVisible = false
            document.removeEventListener('click', this.foo) // 关掉监听，
        },
        styleMenu(menu) {
            if (event.clientX > 1800) {
                menu.style.left = event.clientX - 100 + 'px'
            } else {
                menu.style.left = event.clientX + 1 + 'px'
            }
            document.addEventListener('click', this.foo) // 给整个document新增监听鼠标事件，点击任何位置执行foo方法
            if (event.clientY > 700) {
                menu.style.top = event.clientY - 30 + 'px'
            } else {
                menu.style.top = event.clientY - 10 + 'px'
            }
        },
        // 表集-页大小
        tablePageSize(size) {
            this.tablePage.pageSize = size
            this.searchTableList();
        },
        // 表集-当前页
        tableCurrentPage(currentPage) {
            this.tablePage.currentPage = currentPage
            this.searchTableList();
        },
        // 表集-多选
        tableSelection(selection) {
            var list = new Array();
            for (var i = 0; i < selection.length; i++) {
                list.push(selection[i]['tableName'])
            }
            this.manyTableList = list;
        },
        // 表集-搜索
        searchTableList(isSearch) {
            if (this.dataSourceSin.id) {
                this.tableLoading = true;
                if (isSearch) {
                    this.tablePage.currentPage = 1;
                }

                var tableParam = {
                    currentPage: this.tablePage.currentPage,
                    pageSize: this.tablePage.pageSize,
                    tableName: this.tableName,
                    dataType: this.dataSourceSin.dataType,
                    libraryName: this.dataSourceSin.libraryName,
                    password: this.dataSourceSin.password,
                    url: this.dataSourceSin.url,
                    username: this.dataSourceSin.username
                }

                axiosDoAjax('get', ip + '/table/page', tableParam, function (res) {
                    if (res.code === 0) {
                        vueObj.tableList = res.data.records;
                        vueObj.tablePage.totalCount = res.data.total;
                    }

                    vueObj.tableLoading = false;
                }, function (error) {
                    vueObj.tableLoading = false;
                })
            } else {
                this.showMsg("请选择数据源", 'warning');
            }
        },
        // 表集-行单击事件
        tableRowClick(row, column) {
            this.$refs.table.toggleRowSelection(row);
        },
        // 自动填充-多选
        fillSelection(selection) {
            this.strategy.fillsList = JSON.stringify(selection);
        },
        // 保存自动填充
        saveFillMet() {
            if (this.saveFill.columnName && this.saveFill.fieldFillType) {
                this.saveFillLoading = true;

                axiosDoAjax('post', ip + '/fill/save', this.saveFill, function (res) {
                    if (res.code === 0) {
                        vueObj.getFillList();
                        vueObj.showMsg(res.msg);
                    }

                    vueObj.saveFillLoading = false;
                }, function (error) {
                    vueObj.saveFillLoading = false;
                });
            } else {
                this.showMsg("请填写填充类型和列名...", 'warning');
            }
        },
        // 获取自动填充集
        getFillList() {
            this.fillLoading = true;

            axiosDoAjax('get', ip + '/fill/list', null, function (res) {
                if (res.code === 0) {
                    vueObj.fillList = res.data;
                }

                vueObj.fillLoading = false;
            }, function (error) {
                vueObj.fillLoading = false;
            })
        },
        // 删除自动填充
        deleteFill(id) {
            axiosDoAjax('get', ip + '/fill/delete', { "id": id }, function (res) {
                if (res.code === 0) {
                    vueObj.getFillList();
                    vueObj.showMsg(res.msg);
                }

                vueObj.fillLoading = false;
            }, function (error) {
                vueObj.fillLoading = false;
            });
        },
        // 自动填充-行单击事件
        fillRowClick(row, column) {
            this.$refs.fill.toggleRowSelection(row, column);
        },
        // 策略配置-保存
        saveStrategyMet() {
            if (this.strategyName) {
                this.strategy.name = this.strategyName;
                axiosDoAjax('post', ip + '/strategy/save', this.strategy, function (res) {
                    if (res.code === 0) {
                        vueObj.getStrategyListMet();
                        vueObj.showMsg(res.msg);
                    }
                });
            } else {
                this.showMsg("请填写策略配置名称...", 'warning');
            }
        },
        deleteStrategy(){
            if(this.strategy.id){
                axiosDoAjax('get', ip + '/strategy/delete', { "id": this.strategy.id }, function (res) {
                    if (res.code === 0) {
                        vueObj.$refs.fill.clearSelection();
                        vueObj.strategyName = '';
                        vueObj.strategy = {};
                        vueObj.getStrategyListMet();
                        vueObj.showMsg(res.msg);
                        vueObj.strategyVisible = false;
                    }
                });
            } else {
                this.showMsg("请保存！", 'warning');
            }
        },
        // 策略配置-请求数据集
        getStrategyListMet() {
            axiosDoAjax('get', ip + '/strategy/list', null, function (res) {
                if (res.code === 0) {
                    vueObj.strategyList = [];
                    var list = res.data;
                    for (var i = 0; i < list.length; i++) {
                        var obj = list[i];
                        obj.order = i;
                        vueObj.strategyList.push(obj);
                    }
                }
            });
        },
        // 策略配置-选择
        optionStrategy(value) {
            this.strategy = value;
            this.strategyName = value.name;
            this.strategyVisible = true;

            setTimeout(() => {
                this.$nextTick(() => {
                    if(this.strategy.fillsList){
                        var seFiList = JSON.parse(this.strategy.fillsList);
                        var fiList = this.fillList;
                        this.$refs.fill.clearSelection();

                        for (var i = 0; i < seFiList.length; i++) {
                            for (var j = 0; j < fiList.length; j++) {
                                if (seFiList[i].id == fiList[j].id) {
                                    this.$refs.fill.toggleRowSelection(fiList[j], true)
                                }
                            }
                        }
                    }
                })
            }, 0)
        }
    },

    created: function () {
        initShowMsg(this);
        vueObj = this;
        this.searchDataSource();
        this.getFillList();
        this.getStrategyListMet();
    }
});